Static variable

In computer programming, a static variable is a variable that has been allocated statically — whose lifetime extends across the entire run of the program. This is in contrast to the more ephemeral automatic variables (local variables), whose storage is allocated and deallocated on the call stack; and in contrast to objects whose storage is dynamically allocated.

In many programming languages, such as Pascal, all local variables are automatic and all global variables are allocated statically. In these languages, the term "static variable" is generally not used, since "local" and "global" suffice to cover all the possibilities. Static variables are global, and in languages that do make the distinction between global and static variables, both are typically allocated without any distinction within the compiled code.

In the C programming language, the function of static variables can be illustrated as such:

#include <stdio.h>
 
void func() {
	static int x = 0; // x is initialized only once across three calls of func()
	printf("%d\n", x); // outputs the value of x
	x = x + 1;
}
 
int main(int argc, char * const argv[]) {
	func(); // prints 0
	func(); // prints 1
	func(); // prints 2
	return 0;
}

C and related languages

In the C programming language (and its close descendants such as C++ and Objective-C), static is a reserved word controlling both lifetime (as discussed above) and linkage (visibility). To be precise, static is a storage class (not to be confused with classes in object-oriented programming), as are extern, auto and register (which are also reserved words). Every variable and function has one of these storage classes; if a declaration does not specify the storage class, a context-dependent default is used (eg., extern for all top-level declarations in a source file; auto for variables declared in function bodies).

Storage class Lifetime Linkage
extern static external (whole program)
static static internal (translation unit only)
auto, register function call (none)

In these languages, the term "static variable" has two meanings which are easy to confuse:

  1. (Language-independent) A variable with the same lifetime as the program, as described above; or
  2. (C-family-specific) A variable declared with storage class static

Variables with storage class extern, which include variables declared at top level without an explicit storage class, are "static" in the first meaning but not the second.

As well as specifying static lifetime, declaring a variable as static can have other effects depending on where the declaration occurs:

See also

References